/**
 * ajax请求函数模块
 * 返回值: promise对象(异步返回的数据是: response.data)
 */
import axios from 'axios'
import JSONBIGINT from 'json-bigint'
import Vue from "/src/main"

export const GET = 'GET';
export const POST = 'POST';
export const PUT = 'PUT';
export const DELETE = 'DELETE';

// 默认配置  转换响应数据
axios.defaults.transformResponse = [data => {
    // 对data（后台的原始数据）进行转换
    return JSONBIGINT.parse(data)
}]


export function ajax(url, type, data = {}, configs) {
    return new Promise(function (resolve, reject) {
        // 执行异步ajax请求
        let promise;
        type = type.toUpperCase();
        if (type === GET) {
            // 准备url query参数数据
            let dataStr = '' //数据拼接字符串
            Object.keys(data).forEach(key => {
                if (data[key]) {
                    dataStr += key + '=' + data[key] + '&'
                }
            })
            if (dataStr !== '') {
                dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
                url = url + '?' + dataStr
            }
            // 发送get请求
            promise = axios.get(url, configs)
        } else if (type === POST) {
            // 发送post请求
            promise = axios.post(url, data, configs)
        } else if (type === PUT) {
            //发送put请求
            promise = axios.put(url, data, configs);
        } else if (type === DELETE) {
            //发送delete请求
            promise = axios.delete(url, {
                data
            });
        }
        promise.then(function (response) {
            // 成功了调用resolve()
            resolve(response.data)
        }).catch(function (error) {
            //失败了调用reject()
            reject(error)
        })
    })
}

